package org.truenewx.tnxjee.core.enums.support;

import java.lang.reflect.Field;
import java.util.List;

import org.truenewx.tnxjee.core.enums.annotation.EnumConstantValue;
import org.truenewx.tnxjee.core.util.ClassUtil;

/**
 * 默认的枚举项取值解决器，从@{@link EnumConstantValue}中取值
 *
 * @author jianglei
 */
public class DefaultEnumItemValueResolver implements EnumItemValueResolver {

    @Override
    public String getValue(Field field) {
        if (field != null) {
            EnumConstantValue enumItemValue = field.getAnnotation(EnumConstantValue.class);
            if (enumItemValue != null) {
                return enumItemValue.value();
            }
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T valueOf(Class<T> clazz, String value) {
        if (value != null) {
            List<Field> fields = ClassUtil.getStaticPublicFields(clazz);
            for (Field field : fields) {
                if (clazz.isAssignableFrom(field.getType()) && value.trim().equals(getValue(field))) {
                    try {
                        return (T) field.get(null);
                    } catch (IllegalAccessException ignored) {
                    }
                }
            }
        }
        return null;
    }

}
